package com.lkl.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lkl.Condition;
import com.lkl.entity.Address;
import com.lkl.entity.AddressVO;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据处理类
 * 旧的，用于单省份数据处理
 */
public class DataOldUtil {

    public static void writeToJsonFile(List<Address> data) {
        //定义json对象
        List<AddressVO> addressVOS = new ArrayList<>();
        data.forEach(address -> {
            //查看是否已经有该数据了
            List<AddressVO> collect1 = addressVOS.stream().filter(
                    addressVO -> addressVO.getName().equals(address.getName())).collect(Collectors.toList());
            //大于0，有数据了。获取该数据
            AddressVO addressVO;
            if (collect1.size() > 0) {
                addressVO = collect1.get(0);
//                System.out.println("已有数据：" + addressVO.getName());
            } else {
                //否则创建对象
                addressVO = new AddressVO(address.getCode(), address.getName(), address.getParentCode());
            }
            //根据自身的编码获取子数据
            List<Address> collect = data.stream().filter(
                            address1 -> address1.getParentCode().equals(address.getName()))
                    .collect(Collectors.toList());
            //大于0 ，有子数据
            if (collect.size() > 0) {
                //转换为vo对象
                List<AddressVO> children = collect.stream().map(address1 ->
                        new AddressVO(address1.getCode(), address1.getParentCode(), address1.getParentCode())
                ).collect(Collectors.toList());
                //存为子对象
                addressVO.setChildren(children);
            }
            //存入判断
            String value = address.getName();
            int num = 10;
            if (value.substring(value.length() - num).equals(StringUtils.rightPad("", num, '0'))) {
                addressVOS.add(addressVO);
            }
        });
        System.out.println("结束处理数据");
    }

    /**
     * 转json存入文件
     *
     * @param data      地址数据
     * @param condition 查询条件 ，地区名称，级别
     */
    public static void writeToJsonFile2(List<Address> data, Condition condition) {
        //转换数据
        List<AddressVO> addressVOList = data.stream().map(address ->
                new AddressVO(address.getCode(), address.getName(), address.getParentCode())
        ).collect(Collectors.toList());
        addressVOList.stream().forEach(addressVO -> {
            //判断是否有父对象
            if (!ObjectUtil.isNull(addressVO.getParentCode())) {
                //获取父对象
                List<AddressVO> collect = addressVOList.stream().filter(
                        parentAddress -> addressVO.getParentCode().equals(parentAddress.getCode())
                ).collect(Collectors.toList());
                if (collect.size() > 0) {
                    //添加子对象
                    collect.get(0).getChildren().add(addressVO);
                }
            }
        });
        //转换为json
        String jsonString = JSONObject.toJSONString(addressVOList);
        List<String> collect1 = new ArrayList<>();
        collect1.add(jsonString);

        //路径为 /级别/json/省份-级别.json
        String path = FileUtils.filePath + "/" + condition.getLevel() + "/json";
        //判断文件夹是否存在
        if (!FileUtil.exist(path)) {
            FileUtil.mkdir(path);
        }
        path = path + "/" + Condition.provinceMap.get(condition.getProvince()) + "-" + condition.getLevel() + ".json";
        FileUtil.writeLines(collect1, path, CharsetUtil.CHARSET_UTF_8, true);
    }

    public static void toTreeJson(List<Address> data, Condition condition) {
        System.err.println("开始处理数据");
        System.err.println("===> 数据条数" + data.size());
        System.err.println("===> 条件" + condition);
        //记录开始时间
        DateTime start = new DateTime();
        //定义结果集合
        List<AddressVO> resultList = new ArrayList<>();
        List<AddressVO> list = new ArrayList<>();
        //将所有数据存入map
        Map<String,AddressVO> map = new HashMap<>(data.size());
        data.forEach(address -> {
            AddressVO addressVO = new AddressVO(address.getCode(), address.getName(), address.getParentCode());
            map.put(address.getCode(),addressVO);
            list.add(addressVO);
        });
        long count  = 1L;
        for (AddressVO address : list) {
            //获取父对象
            AddressVO addressVO = map.get(address.getParentCode());
            //不为null,为子对象
            if (addressVO != null) {
                if (null == addressVO.getChildren()) {
                    addressVO.setChildren(new ArrayList<>());
                }
                addressVO.getChildren().add(address);
            } else {
                //为父对象
                resultList.add(address);
            }
            count++;
        }
        toRoot(condition, resultList);
        //有四级，处理子数据
        if ("四级".equals(condition.getLevel())) {
            toCity(condition,resultList);
        }
        System.err.println("《===== 处理数据" + list.size() + "条");
        System.err.println("《===== 根结点" + resultList.size() + "个");
        map.clear();
        list.clear();
        data.clear();
        System.err.println("《===== " + condition.getProvince() +"数据转换已完成");
    }

    /**
     * 适用于省级数据处理
     * @param condition
     * @param resultList
     */
    private static void toRoot(Condition condition, List<AddressVO> resultList) {
        //路径为 /北京/三级/省份-级别.json
        StringBuilder path = new StringBuilder();
        //默认为三级
        String level = "市-区-镇-";
        //根据条件判断是否修改
        if ("四级".equals(condition.getLevel())) {
            level =  "市-区-镇-村-";
        }
        path.append(FileUtils.filePath)
                .append("/")
                .append(condition.getProvince())
                .append("/")
                .append(condition.getLevel())
                .append("/")
                .append(condition.getProvince())
                .append("-")
                .append(level)
                .append(condition.getLevel())
                .append(".json");
        System.out.println("文件路径：" + path);
        List<String> collect1 = new ArrayList<>();
        //获取子数据并转换为json
        collect1.add(JSONObject.toJSONString(resultList.get(0).getChildren(), SerializerFeature.WriteMapNullValue));
        FileUtil.writeLines(collect1, path.toString(), CharsetUtil.CHARSET_UTF_8);
    }

    /**
     * 处理市区数据
     * 只有三级
     * 区-镇-村
     * @param condition
     * @param resultList
     */
    private static void toCity(Condition condition, List<AddressVO> resultList) {
        //获取所有城市级别的数据
        List<AddressVO> data = resultList.get(0).getChildren();
        System.err.println("《===== 处理子数据" + data.size() + "条");
        //路径为 /北京/三级/省份-级别.json
        StringBuilder path = new StringBuilder();
        //默认为三级
        String level = "-区-镇-村-三级.json";
        data.forEach(address -> {
            //根据条件判断是否修改
            path.append(FileUtils.filePath)
                    .append("/")
                    .append(condition.getProvince())  //北京市
                    .append("/")                      // /
                    .append(condition.getProvince())  // 北京市
                    .append("城市数据/")               // 城市数据/
                    .append(address.getName())       //  市辖区
                    .append(level);                 // -区-镇-村-三级.json
            System.out.println("文件路径：" + path);
            List<String> collect1 = new ArrayList<>();
            //获取子数据并转换为json
            collect1.add(JSONObject.toJSONString(address.getChildren(), SerializerFeature.WriteMapNullValue));
            FileUtil.writeLines(collect1, path.toString(), CharsetUtil.CHARSET_UTF_8);
            //设置路径为0
            path.setLength(0);
        });
        System.err.println("《===== 处理子数据完成！");
    }
}
